package com.cooper.common.util;

import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;

import java.security.MessageDigest;
import java.util.UUID;

/**
 * Copyright © 2017 com. All rights reserved.
 *
 * @Title: PasswordUtil.java
 * @Prject: springmvc-mybatis-shiro
 * @Package: com.cooper.common.util
 * @Description: 用户密码工具类
 * @author: JackCooperZ
 * @date: 2017年1月17日 下午5:52:20
 * @version: V1.0
 */
public class PasswordUtil {

    /**
     * @param username 用户名
     * @param express  密码明文
     * @return String 加密后的密码
     * @throws
     * @Title: encrypt
     * @Description: 根据用户名和密码明文加密
     */
    public static String encryptByUsername(String username, String express) {
        String random = new SecureRandomNumberGenerator().nextBytes().toHex();
        String salt = username + random;
        String password = new SimpleHash("SHA-1", express, salt).toString();
        return password;
    }

    /**
     * @param salt    盐
     * @param express 密码明文
     * @return String 加密后的密码
     * @throws
     * @Title: encrypt
     * @Description: 根据密码明文和盐加密
     */
    public static String encryptBySalt(String express, String salt) {
        String password = new SimpleHash("SHA-1", express, salt).toString();
        return password;
    }

    /**
     * 用户Id生成
     */
    public static String generateUserId() {
        return DigestUtils.md5Hex(UUID.randomUUID().toString());
    }

    /**
     * 用户密码Salt生成
     */
    public static String generaterSalt() {
        return DigestUtils.md5Hex(RandomUtil.generateStr(32));
    }


    private static class DigestUtils {

        private static final char[] DIGITS_LOWER =
                {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

        private static final char[] DIGITS_UPPER =
                {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

        private static char[] encodeHex(final byte[] data, final char[] toDigits) {
            final int l = data.length;
            final char[] out = new char[l << 1];
            for (int i = 0, j = 0; i < l; i++) {
                out[j++] = toDigits[(0xF0 & data[i]) >>> 4];
                out[j++] = toDigits[0x0F & data[i]];
            }
            return out;
        }

        public static String md5Hex(String str) {
            return md5Hex(str, false);
        }

        public static String md5Hex(String str, boolean isUpper) {
            try {
                return new String(encodeHex(MessageDigest.getInstance("MD5").digest(str.getBytes("UTF-8")), isUpper ? DIGITS_UPPER : DIGITS_LOWER));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

}
